package com.xsd.awen.shiro;

import com.xsd.awen.domain.po.LoginPo;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class EcsAccessControlFilter extends AccessControlFilter {


    private Logger logger = LoggerFactory.getLogger(EcsAccessControlFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object o) {
        return this.isAccessAllowed(request,response);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception{
        logger.info("no permission");
        response.setContentType("text/plain;charset=UTF-8");//指定类型
        response.getWriter().write("{\"error\":\"no permission\"}");
        return false;
    }

    private boolean isAccessAllowed(ServletRequest request, ServletResponse response){

        HttpServletRequest servletRequest = (HttpServletRequest) request;

        String uri = servletRequest.getRequestURI();
        System.out.println(servletRequest.getRequestURI());

        if ( "/tasks/user/login".equals(uri) ) {
            logger.info("wait for login");
            return true;
        } else {
            Subject subject = this.getSubject(request, response);
            boolean auth = subject != null;
            if( auth ){
                HttpServletRequest req = (HttpServletRequest) request;
                String createUserId = req.getParameter("createUserId");
                String customerId = req.getParameter("customerId");
                String tk = req.getHeader("X-Admin-Token");

                logger.info("check tk:{},{}",subject.getSession().getId(),tk);
                if( tk == null || tk.trim().length() == 0 ){
                    logger.info("check tk is null");
                    auth = false;
                }

                LoginPo loginPo = (LoginPo) subject.getPrincipal();
                if( loginPo == null || loginPo.getTk() == null || !loginPo.getTk().equals(tk) ){
                    logger.info("check tk is not ok");
                    auth = false;
                }

            }

            logger.info("check auth:"+auth);
            return auth;
        }
    }

}